
import {
    DesktopOutlined,
    FileOutlined,
    PieChartOutlined,
    TeamOutlined,
    UserOutlined,
} from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Menu } from 'antd';
import React, { useState } from 'react';

// 编程式导航
import { useNavigate, useLocation } from "react-router-dom"

type MenuItem = Required<MenuProps>['items'][number];

function getItem(
    label: React.ReactNode,
    key: React.Key,
    icon?: React.ReactNode,
    children?: MenuItem[],
): MenuItem {
    return {
        key,
        icon,
        children,
        label,
    } as MenuItem;
}

const items: MenuItem[] = [
    getItem('栏目一', '/page1', <PieChartOutlined />),
    getItem('栏目二', '/page2', <DesktopOutlined />),
    getItem('栏目三', '/page3', <UserOutlined />, [
        getItem('栏目 301', '/page3/page301'),
        getItem('栏目 302', '/page3/page302'),
        getItem('栏目 303', '/page3/page303'),
    ]),
    getItem('栏目四', '/page4', <TeamOutlined />, [getItem('栏目 401', '/page4/page401'), getItem('栏目 402', '/page4/page402')]),
    getItem('栏目五', '/page5', <FileOutlined />),
];

const Com: React.FC = () => {
    const navigateTo = useNavigate()

    const menuClick = (e: { key: string }) => {
        console.log("点击了", e.key)
        navigateTo(e.key)

    }

    const currentRounteInfo = useLocation()
    // console.log(currentRounteInfo)
    // {
    //     "pathname": "/page3/page301",
    //     "search": "",
    //     "hash": "",
    //     "state": null,
    //     "key": "1yk0buqy"
    // }

    function firstOpenkey(): string {
        for (let i = 0; i < items.length; i++) {
            //判断找到情况
            if (items[i]!['children'] && items[i]!['children'].length > 0 && items[i]!['children'].find(findkey)) {
                return items[i]!.key as string;
            }
        }
        return ''
    }
    function findkey(obj: { key: string }) {
        return obj.key === currentRounteInfo.pathname
    }
    console.log(firstOpenkey())
    // 设置展开项的初始值
    let [openKeys, setOpenKeys] = useState([firstOpenkey()]);

    // console.log(expand)
    // openKeys = [currentRounteInfo.pathname]
    // 菜单展开和回收的时间
    const handleOpenChange = (keys: string[]) => {
        // 记录了当前那一项是展开的
        setOpenKeys([keys[keys.length - 1]])
    }
    return (
        <Menu theme="dark" defaultSelectedKeys={[currentRounteInfo.pathname]} mode="inline" items={items} onClick={menuClick} onOpenChange={handleOpenChange} openKeys={openKeys} />
    )
}
export default Com